# -*- coding: utf-8 -*-
"""
配置文件自动修复工具
提供智能配置修复、建议生成和配置优化功能
"""

import os
import sys
import json
import time
import shutil
import argparse
from pathlib import Path
from typing import Dict, List, Any, Optional, Tuple
from datetime import datetime

# 尝试导入统一日志系统
try:
    from config.unified_logger import get_logger
    logger = get_logger(__name__)
except ImportError:
    import logging
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)

# 尝试导入配置验证器
try:
    from config.config_validator import ConfigValidator
    CONFIG_VALIDATOR_AVAILABLE = True
except ImportError:
    CONFIG_VALIDATOR_AVAILABLE = False

class ConfigAutoRepair:
    """配置文件自动修复器"""
    
    def __init__(self):
        self.repair_rules = self._load_repair_rules()
        self.backup_dir = "config_backups"
        self.repair_history = []
        
    def _load_repair_rules(self) -> Dict[str, Any]:
        """加载修复规则"""
        return {
            'json_syntax': {
                'missing_quotes': {
                    'pattern': r'(\w+)(\s*:\s*)',
                    'replacement': r'"\1"\2',
                    'description': '为键名添加引号'
                },
                'trailing_comma': {
                    'pattern': r',(\s*[}\]])',
                    'replacement': r'\1',
                    'description': '移除尾随逗号'
                },
                'single_quotes': {
                    'pattern': r"'([^']*)'",
                    'replacement': r'"\1"',
                    'description': '将单引号替换为双引号'
                }
            },
            'security_settings': {
                'weak_encryption': {
                    'check': lambda config: config.get('encryption', {}).get('algorithm') in ['md5', 'sha1'],
                    'fix': lambda config: self._fix_weak_encryption(config),
                    'description': '升级弱加密算法'
                },
                'insecure_ports': {
                    'check': lambda config: any(
                        port in [21, 23, 80, 135, 139, 445] 
                        for port in self._extract_ports(config)
                    ),
                    'fix': lambda config: self._fix_insecure_ports(config),
                    'description': '修复不安全端口配置'
                },
                'default_passwords': {
                    'check': lambda config: self._has_default_passwords(config),
                    'fix': lambda config: self._fix_default_passwords(config),
                    'description': '移除默认密码'
                }
            },
            'performance_optimization': {
                'large_timeouts': {
                    'check': lambda config: any(
                        timeout > 300 
                        for timeout in self._extract_timeouts(config)
                    ),
                    'fix': lambda config: self._optimize_timeouts(config),
                    'description': '优化超时设置'
                },
                'excessive_retries': {
                    'check': lambda config: any(
                        retries > 10 
                        for retries in self._extract_retries(config)
                    ),
                    'fix': lambda config: self._optimize_retries(config),
                    'description': '优化重试次数'
                }
            },
            'path_validation': {
                'invalid_paths': {
                    'check': lambda config: self._has_invalid_paths(config),
                    'fix': lambda config: self._fix_invalid_paths(config),
                    'description': '修复无效路径'
                },
                'relative_paths': {
                    'check': lambda config: self._has_relative_paths(config),
                    'fix': lambda config: self._convert_to_absolute_paths(config),
                    'description': '将相对路径转换为绝对路径'
                }
            }
        }
    
    def analyze_config(self, config_path: str) -> Dict[str, Any]:
        """分析配置文件并生成修复建议"""
        analysis_result = {
            'file_path': config_path,
            'timestamp': datetime.now().isoformat(),
            'issues_found': [],
            'repair_suggestions': [],
            'severity_levels': {'critical': 0, 'high': 0, 'medium': 0, 'low': 0},
            'auto_fixable': [],
            'manual_review_required': []
        }
        
        try:
            # 检查文件是否存在
            if not os.path.exists(config_path):
                analysis_result['issues_found'].append({
                    'type': 'file_not_found',
                    'severity': 'critical',
                    'message': f'配置文件不存在: {config_path}',
                    'auto_fixable': False
                })
                return analysis_result
            
            # 尝试解析配置文件
            config_content = None
            parse_error = None
            
            if config_path.endswith('.json'):
                config_content, parse_error = self._parse_json_config(config_path)
            else:
                # 尝试作为文本文件读取
                try:
                    with open(config_path, 'r', encoding='utf-8') as f:
                        config_content = f.read()
                except Exception as e:
                    parse_error = str(e)
            
            # 如果解析失败，尝试语法修复
            if parse_error:
                analysis_result['issues_found'].append({
                    'type': 'parse_error',
                    'severity': 'high',
                    'message': f'配置文件解析失败: {parse_error}',
                    'auto_fixable': True
                })
                
                # 尝试自动修复语法错误
                if config_path.endswith('.json'):
                    fixed_content = self._fix_json_syntax(config_path)
                    if fixed_content:
                        analysis_result['repair_suggestions'].append({
                            'type': 'syntax_fix',
                            'description': 'JSON语法自动修复',
                            'action': 'replace_content',
                            'new_content': fixed_content
                        })
            
            # 如果成功解析，进行深度分析
            if config_content and isinstance(config_content, dict):
                self._analyze_config_content(config_content, analysis_result)
            
            # 使用配置验证器（如果可用）
            if CONFIG_VALIDATOR_AVAILABLE:
                validator = ConfigValidator()
                is_valid, errors, suggestions = validator.validate_config_file(config_path)
                
                for error in errors:
                    analysis_result['issues_found'].append({
                        'type': 'validation_error',
                        'severity': 'medium',
                        'message': error,
                        'auto_fixable': False
                    })
                
                for suggestion in suggestions:
                    analysis_result['repair_suggestions'].append({
                        'type': 'validation_suggestion',
                        'description': suggestion,
                        'action': 'manual_review'
                    })
            
            # 统计严重程度
            for issue in analysis_result['issues_found']:
                severity = issue.get('severity', 'low')
                analysis_result['severity_levels'][severity] += 1
                
                if issue.get('auto_fixable', False):
                    analysis_result['auto_fixable'].append(issue)
                else:
                    analysis_result['manual_review_required'].append(issue)
            
            return analysis_result
            
        except Exception as e:
            logger.error(f"分析配置文件失败: {config_path}, 错误: {e}")
            analysis_result['issues_found'].append({
                'type': 'analysis_error',
                'severity': 'critical',
                'message': f'分析过程中发生错误: {e}',
                'auto_fixable': False
            })
            return analysis_result
    
    def _parse_json_config(self, config_path: str) -> Tuple[Optional[Dict], Optional[str]]:
        """解析JSON配置文件"""
        try:
            with open(config_path, 'r', encoding='utf-8') as f:
                content = json.load(f)
            return content, None
        except json.JSONDecodeError as e:
            return None, f"JSON解析错误: {e}"
        except Exception as e:
            return None, f"文件读取错误: {e}"
    
    def _fix_json_syntax(self, config_path: str) -> Optional[str]:
        """修复JSON语法错误"""
        try:
            with open(config_path, 'r', encoding='utf-8') as f:
                content = f.read()
            
            original_content = content
            
            # 应用JSON语法修复规则
            for rule_name, rule in self.repair_rules['json_syntax'].items():
                import re
                content = re.sub(rule['pattern'], rule['replacement'], content)
            
            # 验证修复后的JSON
            try:
                json.loads(content)
                logger.info(f"JSON语法修复成功: {config_path}")
                return content
            except json.JSONDecodeError:
                logger.warning(f"JSON语法修复失败: {config_path}")
                return None
                
        except Exception as e:
            logger.error(f"修复JSON语法时发生错误: {e}")
            return None
    
    def _analyze_config_content(self, config: Dict[str, Any], analysis_result: Dict[str, Any]):
        """分析配置内容"""
        # 检查安全设置
        for rule_name, rule in self.repair_rules['security_settings'].items():
            if rule['check'](config):
                analysis_result['issues_found'].append({
                    'type': 'security_issue',
                    'rule': rule_name,
                    'severity': 'high',
                    'message': rule['description'],
                    'auto_fixable': True
                })
        
        # 检查性能优化
        for rule_name, rule in self.repair_rules['performance_optimization'].items():
            if rule['check'](config):
                analysis_result['issues_found'].append({
                    'type': 'performance_issue',
                    'rule': rule_name,
                    'severity': 'medium',
                    'message': rule['description'],
                    'auto_fixable': True
                })
        
        # 检查路径验证
        for rule_name, rule in self.repair_rules['path_validation'].items():
            if rule['check'](config):
                analysis_result['issues_found'].append({
                    'type': 'path_issue',
                    'rule': rule_name,
                    'severity': 'medium',
                    'message': rule['description'],
                    'auto_fixable': True
                })
    
    def auto_repair_config(self, config_path: str, backup: bool = True) -> Dict[str, Any]:
        """自动修复配置文件"""
        repair_result = {
            'success': False,
            'backup_path': None,
            'repairs_applied': [],
            'errors': [],
            'warnings': []
        }
        
        try:
            # 创建备份
            if backup:
                backup_path = self._create_backup(config_path)
                repair_result['backup_path'] = backup_path
            
            # 分析配置文件
            analysis = self.analyze_config(config_path)
            
            # 如果没有可自动修复的问题，直接返回
            if not analysis['auto_fixable']:
                repair_result['warnings'].append('没有发现可自动修复的问题')
                repair_result['success'] = True
                return repair_result
            
            # 读取原始配置
            if config_path.endswith('.json'):
                config_content, parse_error = self._parse_json_config(config_path)
                
                # 如果解析失败，尝试语法修复
                if parse_error:
                    fixed_content = self._fix_json_syntax(config_path)
                    if fixed_content:
                        with open(config_path, 'w', encoding='utf-8') as f:
                            f.write(fixed_content)
                        repair_result['repairs_applied'].append('JSON语法修复')
                        
                        # 重新解析修复后的配置
                        config_content, parse_error = self._parse_json_config(config_path)
                
                if config_content:
                    # 应用内容修复
                    modified = False
                    
                    # 安全设置修复
                    for rule_name, rule in self.repair_rules['security_settings'].items():
                        if rule['check'](config_content):
                            config_content = rule['fix'](config_content)
                            repair_result['repairs_applied'].append(f'安全修复: {rule["description"]}')
                            modified = True
                    
                    # 性能优化修复
                    for rule_name, rule in self.repair_rules['performance_optimization'].items():
                        if rule['check'](config_content):
                            config_content = rule['fix'](config_content)
                            repair_result['repairs_applied'].append(f'性能优化: {rule["description"]}')
                            modified = True
                    
                    # 路径修复
                    for rule_name, rule in self.repair_rules['path_validation'].items():
                        if rule['check'](config_content):
                            config_content = rule['fix'](config_content)
                            repair_result['repairs_applied'].append(f'路径修复: {rule["description"]}')
                            modified = True
                    
                    # 保存修复后的配置
                    if modified:
                        with open(config_path, 'w', encoding='utf-8') as f:
                            json.dump(config_content, f, indent=2, ensure_ascii=False)
                        logger.info(f"配置文件修复完成: {config_path}")
            
            repair_result['success'] = True
            
            # 记录修复历史
            self.repair_history.append({
                'timestamp': datetime.now().isoformat(),
                'file_path': config_path,
                'repairs_applied': repair_result['repairs_applied'],
                'backup_path': repair_result['backup_path']
            })
            
            return repair_result
            
        except Exception as e:
            error_msg = f"自动修复配置文件失败: {e}"
            logger.error(error_msg)
            repair_result['errors'].append(error_msg)
            return repair_result
    
    def _create_backup(self, config_path: str) -> str:
        """创建配置文件备份"""
        try:
            # 确保备份目录存在
            os.makedirs(self.backup_dir, exist_ok=True)
            
            # 生成备份文件名
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
            filename = os.path.basename(config_path)
            backup_filename = f"{filename}.backup_{timestamp}"
            backup_path = os.path.join(self.backup_dir, backup_filename)
            
            # 复制文件
            shutil.copy2(config_path, backup_path)
            logger.info(f"配置文件备份已创建: {backup_path}")
            
            return backup_path
            
        except Exception as e:
            logger.error(f"创建备份失败: {e}")
            raise
    
    def _fix_weak_encryption(self, config: Dict[str, Any]) -> Dict[str, Any]:
        """修复弱加密算法"""
        if 'encryption' in config:
            encryption = config['encryption']
            if encryption.get('algorithm') in ['md5', 'sha1']:
                encryption['algorithm'] = 'sha256'
                logger.info("已将弱加密算法升级为SHA256")
        return config
    
    def _extract_ports(self, config: Dict[str, Any]) -> List[int]:
        """提取配置中的端口号"""
        ports = []
        
        def extract_recursive(obj):
            if isinstance(obj, dict):
                for key, value in obj.items():
                    if 'port' in key.lower() and isinstance(value, int):
                        ports.append(value)
                    elif isinstance(value, (dict, list)):
                        extract_recursive(value)
            elif isinstance(obj, list):
                for item in obj:
                    extract_recursive(item)
        
        extract_recursive(config)
        return ports
    
    def _fix_insecure_ports(self, config: Dict[str, Any]) -> Dict[str, Any]:
        """修复不安全端口配置"""
        insecure_ports = [21, 23, 80, 135, 139, 445]
        secure_alternatives = {21: 22, 23: 22, 80: 443, 135: 993, 139: 993, 445: 993}
        
        def fix_recursive(obj):
            if isinstance(obj, dict):
                for key, value in obj.items():
                    if 'port' in key.lower() and isinstance(value, int) and value in insecure_ports:
                        obj[key] = secure_alternatives.get(value, value + 1000)
                        logger.info(f"已将不安全端口 {value} 修改为 {obj[key]}")
                    elif isinstance(value, (dict, list)):
                        fix_recursive(value)
            elif isinstance(obj, list):
                for item in obj:
                    fix_recursive(item)
        
        fix_recursive(config)
        return config
    
    def _has_default_passwords(self, config: Dict[str, Any]) -> bool:
        """检查是否包含默认密码"""
        default_passwords = ['admin', 'password', '123456', 'root', 'default']
        
        def check_recursive(obj):
            if isinstance(obj, dict):
                for key, value in obj.items():
                    if 'password' in key.lower() and isinstance(value, str):
                        if value.lower() in default_passwords:
                            return True
                    elif isinstance(value, (dict, list)):
                        if check_recursive(value):
                            return True
            elif isinstance(obj, list):
                for item in obj:
                    if check_recursive(item):
                        return True
            return False
        
        return check_recursive(config)
    
    def _fix_default_passwords(self, config: Dict[str, Any]) -> Dict[str, Any]:
        """修复默认密码"""
        default_passwords = ['admin', 'password', '123456', 'root', 'default']
        
        def fix_recursive(obj):
            if isinstance(obj, dict):
                for key, value in obj.items():
                    if 'password' in key.lower() and isinstance(value, str):
                        if value.lower() in default_passwords:
                            obj[key] = "CHANGE_ME_" + str(int(time.time()))
                            logger.warning(f"已移除默认密码，请手动设置: {key}")
                    elif isinstance(value, (dict, list)):
                        fix_recursive(value)
            elif isinstance(obj, list):
                for item in obj:
                    fix_recursive(item)
        
        fix_recursive(config)
        return config
    
    def _extract_timeouts(self, config: Dict[str, Any]) -> List[int]:
        """提取配置中的超时设置"""
        timeouts = []
        
        def extract_recursive(obj):
            if isinstance(obj, dict):
                for key, value in obj.items():
                    if 'timeout' in key.lower() and isinstance(value, (int, float)):
                        timeouts.append(int(value))
                    elif isinstance(value, (dict, list)):
                        extract_recursive(value)
            elif isinstance(obj, list):
                for item in obj:
                    extract_recursive(item)
        
        extract_recursive(config)
        return timeouts
    
    def _optimize_timeouts(self, config: Dict[str, Any]) -> Dict[str, Any]:
        """优化超时设置"""
        def optimize_recursive(obj):
            if isinstance(obj, dict):
                for key, value in obj.items():
                    if 'timeout' in key.lower() and isinstance(value, (int, float)):
                        if value > 300:  # 超过5分钟
                            obj[key] = 300
                            logger.info(f"已优化超时设置 {key}: {value} -> 300")
                    elif isinstance(value, (dict, list)):
                        optimize_recursive(value)
            elif isinstance(obj, list):
                for item in obj:
                    optimize_recursive(item)
        
        optimize_recursive(config)
        return config
    
    def _extract_retries(self, config: Dict[str, Any]) -> List[int]:
        """提取配置中的重试次数"""
        retries = []
        
        def extract_recursive(obj):
            if isinstance(obj, dict):
                for key, value in obj.items():
                    if 'retry' in key.lower() or 'retries' in key.lower():
                        if isinstance(value, int):
                            retries.append(value)
                    elif isinstance(value, (dict, list)):
                        extract_recursive(value)
            elif isinstance(obj, list):
                for item in obj:
                    extract_recursive(item)
        
        extract_recursive(config)
        return retries
    
    def _optimize_retries(self, config: Dict[str, Any]) -> Dict[str, Any]:
        """优化重试次数"""
        def optimize_recursive(obj):
            if isinstance(obj, dict):
                for key, value in obj.items():
                    if ('retry' in key.lower() or 'retries' in key.lower()) and isinstance(value, int):
                        if value > 10:
                            obj[key] = 10
                            logger.info(f"已优化重试次数 {key}: {value} -> 10")
                    elif isinstance(value, (dict, list)):
                        optimize_recursive(value)
            elif isinstance(obj, list):
                for item in obj:
                    optimize_recursive(item)
        
        optimize_recursive(config)
        return config
    
    def _has_invalid_paths(self, config: Dict[str, Any]) -> bool:
        """检查是否包含无效路径"""
        def check_recursive(obj):
            if isinstance(obj, dict):
                for key, value in obj.items():
                    if 'path' in key.lower() and isinstance(value, str):
                        if not os.path.exists(value):
                            return True
                    elif isinstance(value, (dict, list)):
                        if check_recursive(value):
                            return True
            elif isinstance(obj, list):
                for item in obj:
                    if check_recursive(item):
                        return True
            return False
        
        return check_recursive(config)
    
    def _fix_invalid_paths(self, config: Dict[str, Any]) -> Dict[str, Any]:
        """修复无效路径"""
        def fix_recursive(obj):
            if isinstance(obj, dict):
                for key, value in obj.items():
                    if 'path' in key.lower() and isinstance(value, str):
                        if not os.path.exists(value):
                            # 尝试创建目录
                            try:
                                if not value.endswith(('.txt', '.log', '.json', '.xml', '.conf')):
                                    os.makedirs(value, exist_ok=True)
                                    logger.info(f"已创建目录: {value}")
                                else:
                                    # 创建父目录
                                    parent_dir = os.path.dirname(value)
                                    if parent_dir:
                                        os.makedirs(parent_dir, exist_ok=True)
                                        logger.info(f"已创建父目录: {parent_dir}")
                            except Exception as e:
                                logger.warning(f"无法创建路径 {value}: {e}")
                    elif isinstance(value, (dict, list)):
                        fix_recursive(value)
            elif isinstance(obj, list):
                for item in obj:
                    fix_recursive(item)
        
        fix_recursive(config)
        return config
    
    def _has_relative_paths(self, config: Dict[str, Any]) -> bool:
        """检查是否包含相对路径"""
        def check_recursive(obj):
            if isinstance(obj, dict):
                for key, value in obj.items():
                    if 'path' in key.lower() and isinstance(value, str):
                        if not os.path.isabs(value):
                            return True
                    elif isinstance(value, (dict, list)):
                        if check_recursive(value):
                            return True
            elif isinstance(obj, list):
                for item in obj:
                    if check_recursive(item):
                        return True
            return False
        
        return check_recursive(config)
    
    def _convert_to_absolute_paths(self, config: Dict[str, Any]) -> Dict[str, Any]:
        """将相对路径转换为绝对路径"""
        def convert_recursive(obj):
            if isinstance(obj, dict):
                for key, value in obj.items():
                    if 'path' in key.lower() and isinstance(value, str):
                        if not os.path.isabs(value):
                            abs_path = os.path.abspath(value)
                            obj[key] = abs_path
                            logger.info(f"已将相对路径转换为绝对路径: {value} -> {abs_path}")
                    elif isinstance(value, (dict, list)):
                        convert_recursive(value)
            elif isinstance(obj, list):
                for item in obj:
                    convert_recursive(item)
        
        convert_recursive(config)
        return config
    
    def generate_repair_report(self, config_path: str, output_path: str = None) -> str:
        """生成修复报告"""
        analysis = self.analyze_config(config_path)
        
        report_lines = []
        report_lines.append("="*80)
        report_lines.append("配置文件自动修复报告")
        report_lines.append("="*80)
        report_lines.append(f"配置文件: {config_path}")
        report_lines.append(f"分析时间: {analysis['timestamp']}")
        report_lines.append("")
        
        # 问题统计
        severity_levels = analysis['severity_levels']
        total_issues = sum(severity_levels.values())
        report_lines.append(f"问题统计: 总计 {total_issues} 个问题")
        for severity, count in severity_levels.items():
            if count > 0:
                report_lines.append(f"  {severity.upper()}: {count}")
        report_lines.append("")
        
        # 可自动修复的问题
        auto_fixable = analysis['auto_fixable']
        if auto_fixable:
            report_lines.append(f"可自动修复的问题 ({len(auto_fixable)}):")
            for i, issue in enumerate(auto_fixable, 1):
                report_lines.append(f"  {i}. [{issue['severity'].upper()}] {issue['message']}")
        else:
            report_lines.append("✅ 没有发现可自动修复的问题")
        report_lines.append("")
        
        # 需要手动审查的问题
        manual_review = analysis['manual_review_required']
        if manual_review:
            report_lines.append(f"需要手动审查的问题 ({len(manual_review)}):")
            for i, issue in enumerate(manual_review, 1):
                report_lines.append(f"  {i}. [{issue['severity'].upper()}] {issue['message']}")
        report_lines.append("")
        
        # 修复建议
        suggestions = analysis['repair_suggestions']
        if suggestions:
            report_lines.append(f"修复建议 ({len(suggestions)}):")
            for i, suggestion in enumerate(suggestions, 1):
                report_lines.append(f"  {i}. {suggestion['description']}")
        report_lines.append("")
        
        report_lines.append("="*80)
        
        report_content = "\n".join(report_lines)
        
        # 保存报告
        if output_path:
            try:
                with open(output_path, 'w', encoding='utf-8') as f:
                    f.write(report_content)
                logger.info(f"修复报告已保存到: {output_path}")
            except Exception as e:
                logger.error(f"保存修复报告失败: {e}")
        
        return report_content

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="配置文件自动修复工具")
    parser.add_argument('config_path', help="配置文件路径")
    parser.add_argument('--analyze', action='store_true', help="仅分析配置文件，不进行修复")
    parser.add_argument('--repair', action='store_true', help="自动修复配置文件")
    parser.add_argument('--no-backup', action='store_true', help="不创建备份文件")
    parser.add_argument('--report', help="生成修复报告的输出路径")
    parser.add_argument('--verbose', action='store_true', help="详细输出")
    
    args = parser.parse_args()
    
    if args.verbose:
        logging.getLogger().setLevel(logging.DEBUG)
    
    # 创建修复器实例
    repairer = ConfigAutoRepair()
    
    try:
        if args.analyze or args.report:
            # 分析模式
            print(f"正在分析配置文件: {args.config_path}")
            analysis = repairer.analyze_config(args.config_path)
            
            print(f"\n分析结果:")
            print(f"  发现问题: {len(analysis['issues_found'])}")
            print(f"  可自动修复: {len(analysis['auto_fixable'])}")
            print(f"  需要手动审查: {len(analysis['manual_review_required'])}")
            
            # 生成报告
            if args.report:
                report = repairer.generate_repair_report(args.config_path, args.report)
                print(f"\n修复报告已保存到: {args.report}")
            else:
                report = repairer.generate_repair_report(args.config_path)
                print("\n" + report)
        
        if args.repair:
            # 修复模式
            print(f"正在修复配置文件: {args.config_path}")
            backup = not args.no_backup
            
            result = repairer.auto_repair_config(args.config_path, backup)
            
            if result['success']:
                print("✅ 配置文件修复完成")
                if result['backup_path']:
                    print(f"备份文件: {result['backup_path']}")
                if result['repairs_applied']:
                    print("应用的修复:")
                    for repair in result['repairs_applied']:
                        print(f"  - {repair}")
                if result['warnings']:
                    print("警告:")
                    for warning in result['warnings']:
                        print(f"  - {warning}")
            else:
                print("❌ 配置文件修复失败")
                for error in result['errors']:
                    print(f"错误: {error}")
        
        if not args.analyze and not args.repair and not args.report:
            print("请指定操作模式: --analyze, --repair 或 --report")
            parser.print_help()
    
    except KeyboardInterrupt:
        print("\n操作已取消")
        sys.exit(1)
    except Exception as e:
        print(f"发生错误: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()